package com.chenglu.android.restaurant.shop.details;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.cart.bean.CartBean;
import com.chenglu.android.common.base.BaseFullScreenActivity;
import com.chenglu.android.common.utils.GlideUtils;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.MoneyUtils;
import com.chenglu.android.common.utils.StatusBarUtil;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.goodsinfo.GoodsInfoActivity;
import com.chenglu.android.goodsinfo.adapter.InfoCouponAdapter;
import com.chenglu.android.goodsinfo.bean.ShopCouponPage;
import com.chenglu.android.mine.bean.CommonDataBean;
import com.chenglu.android.restaurant.adapter.InfoShopCouponAdapter;
import com.chenglu.android.restaurant.adapter.ShopCouponListAdapter;
import com.chenglu.android.restaurant.bean.CurrentShopsInfoBean;
import com.chenglu.android.restaurant.bean.GoodscategorylisBean;
import com.chenglu.android.restaurant.bean.ReviewTypeCountBean;
import com.chenglu.android.restaurant.bean.ShopReviewPageBean;
import com.chenglu.android.restaurant.event.ReviewTypeCountEvent;
import com.chenglu.android.restaurant.mvp.contract.RestaurantShopContract;
import com.chenglu.android.restaurant.mvp.presenter.RestaurantShopPresenter;
import com.chenglu.android.restaurant.shop.fragment.EvaluateFragment;
import com.chenglu.android.restaurant.shop.fragment.MenuScrollFragment;
import com.chenglu.android.restaurant.shop.fragment.ShopFragment;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.animator.PopupAnimator;
import com.lxj.xpopup.core.BottomPopupView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopDetailsActivity extends BaseFullScreenActivity<RestaurantShopPresenter> implements RestaurantShopContract.View {
    public static final String TENANTID = "tenantid";
    @BindView(R.id.iv_shop_details_toolbar_bg)
    ImageView ivShopDetailsToolbarBg;
    @BindView(R.id.tv_toolbar_title)
    TextView tvToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.collapsingToolbarLayout)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;
    @BindView(R.id.tv_item_score)
    TextView tvItemScore;
    @BindView(R.id.tv_item_sell)
    TextView tvItemSell;
    @BindView(R.id.item_rv_coupon)
    RecyclerView itemRvCoupon;
    @BindView(R.id.ll_coupon_more)
    LinearLayout llCouponMore;
    @BindView(R.id.tl_2)
    SlidingTabLayout tl2;
    @BindView(R.id.vp)
    ViewPager vp;

    @BindView(R.id.rl_shop_details_name)
    RelativeLayout rlShopDetailsName;
    @BindView(R.id.ll_shop_details_score)
    LinearLayout llShopDetailsScore;
    @BindView(R.id.ll_shop_details_coupon)
    LinearLayout llShopDetailsCoupon;


    public String tenantId;
    private final String[] titles = {
            "点菜", "评价", "商家故事"
    };
    @BindView(R.id.tv_shop_number)
    TextView tvShopNumber;
    @BindView(R.id.fl_cart)
    FrameLayout flCart;
    @BindView(R.id.tv_rmb)
    TextView tvRmb;
    @BindView(R.id.tv_item_price)
    TextView tvItemPrice;
    @BindView(R.id.ll_prcie)
    LinearLayout llPrcie;
    @BindView(R.id.tv_delivery_fee)
    TextView tvDeliveryFee;
    @BindView(R.id.tv_cart_settleaccounts)
    TextView tvCartSettleaccounts;
    @BindView(R.id.rl_shop_details_cart)
    RelativeLayout rlShopDetailsCart;

    int count = 0;

    private boolean isHasShopCoupon = false;
    public CurrentShopsInfoBean currentShopsInfoBean;
    public GoodscategorylisBean goodscategorylisBean;
    public ReviewTypeCountBean reviewTypeCountBean;
    public  Handler handler=new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_details);
        ButterKnife.bind(this);
        mPresenter = new RestaurantShopPresenter();
        mPresenter.attachView(this);
        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);
//
        tenantId = getIntent().getStringExtra(TENANTID);
        LogUtils.v("tenantId:" + tenantId);
        mPresenter.getCurrentShopsInfo(tenantId);
        mPresenter.getReviewTypeCount(tenantId);


//
////        toolbar.setTitle("标1题");
////        toolbar.setTitleTextAppearance(this, R.style.Toolbar_TitleText);
        toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_black_back));
////        toolbar.inflateMenu(R.menu.toolbar_menu);
//
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                // 处理滑动事件
                // 根据 verticalOffset 的值执行不同的操作
                if (verticalOffset == 0) {
                    // 完全展开
//                    LogUtils.e("完全展开"+verticalOffset);
                    EventBus.getDefault().post(new ReviewTypeCountEvent(4));
//                    EventBus.getDefault().post(new ReviewTypeCountEvent(2));
                } else if (Math.abs(verticalOffset) >= (appBarLayout.getTotalScrollRange())) {
                    // 完全折叠
//                    LogUtils.e("完全折叠" + verticalOffset);
                    EventBus.getDefault().post(new ReviewTypeCountEvent(3));
                    tvToolbarTitle.setVisibility(View.VISIBLE);
                } else if (Math.abs(verticalOffset) <= (appBarLayout.getTotalScrollRange() / 2)) {
                    // 部分折叠
                    // 根据偏移量执行其他操作
//                    LogUtils.e("部分折叠"+verticalOffset);
//                    EventBus.getDefault().post(new ReviewTypeCountEvent(2));
                    tvToolbarTitle.setVisibility(View.INVISIBLE);
                }
            }
        });
        //设置导航按钮的点击事件
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initVp();
    }

    private ArrayList<Fragment> fragments = new ArrayList<>();

    private MyPagerAdapter mAdapter;

    private void initVp() {
        fragments.add(MenuScrollFragment.getInstance(this));
        fragments.add(EvaluateFragment.getInstance(this));
        fragments.add(ShopFragment.getInstance(this));
        mAdapter = new MyPagerAdapter(getSupportFragmentManager());
        vp.setAdapter(mAdapter);
        tl2.setViewPager(vp);
        vp.setCurrentItem(0);
//        vp.setOffscreenPageLimit(fragments.size());
        tl2.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                EventBus.getDefault().post(new ReviewTypeCountEvent(1));
                EventBus.getDefault().post(new ReviewTypeCountEvent(2));
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                EventBus.getDefault().post(new ReviewTypeCountEvent(1));
                EventBus.getDefault().post(new ReviewTypeCountEvent(2));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }


    @Override
    public void getCurrentShopsInfo(CurrentShopsInfoBean bean) {
        currentShopsInfoBean = bean;

        GlideUtils.setImageView(mContext, bean.getData().getShopsImage(), ivShopDetailsToolbarBg);
        tvGoodsName.setText(bean.getData().getShopsName());
        tvToolbarTitle.setText(bean.getData().getShopsName());
        tvItemScore.setText(Utils.formatZeroNumber(bean.getData().getScore() + "") + "分");
        tvItemSell.setText("销量 " + bean.getData().getSalesAmount());

        if (bean.getData().getCouponList().size() > 0) {
            llShopDetailsCoupon.setVisibility(View.VISIBLE);
            isHasShopCoupon = true;
            ShopCouponListAdapter shopCouponListAdapter = new ShopCouponListAdapter(mContext, bean.getData().getCouponList());
            itemRvCoupon.setLayoutManager(new LinearLayoutManager(mContext));
            itemRvCoupon.setAdapter(shopCouponListAdapter);
        } else {
            isHasShopCoupon = false;
            llShopDetailsCoupon.setVisibility(View.GONE);
        }

        if (bean.getData().getIsCollect() == 0) {
            ivCollect.setBackground(getResources().getDrawable(R.drawable.icon_start_default));
        } else {
            ivCollect.setBackground(getResources().getDrawable(R.drawable.icon_start_press));
        }
        //运费
        tvDeliveryFee.setText("配送费:¥" + bean.getData().getPostFee());

        EventBus.getDefault().post(new ReviewTypeCountEvent(1));
        //请求购物车的接口
        getShopsCart();

    }

    public void getShopsCart() {
        if (isLogin) {
            //显示数量
            mPresenter.getShopsCartList(getToken(), tenantId);

        } else {
            ToastUtils.show("请先登录");
        }
    }

    @Override
    public void getGoodscategoryList(GoodscategorylisBean bean) {
        goodscategorylisBean = bean;
    }

    @Override
    public void getReviewTypeCount(ReviewTypeCountBean bean) {
        titles[1] = "评价(" + bean.getData().getAllCount() + ")";
        tl2.notifyDataSetChanged();
        reviewTypeCountBean = bean;
        EventBus.getDefault().post(new ReviewTypeCountEvent(2));
    }

    @Override
    public void getShopReviewPage(ShopReviewPageBean bean) {

    }

    @Override
    public void getAddCartShop(CommonDataBean bean) {

    }

    @Override
    public void getShopsCartList(CartBean bean) {
        tvItemPrice.setText("0");
        String sum = "0.00";
        count = 0;
        if (bean.getData() != null) {
            for (int i = 0; i < bean.getData().get(0).getShoppingTrolleyVOList().size(); i++) {
                sum = MoneyUtils.Algorithm.add(sum, MoneyUtils.Algorithm.multiply(bean.getData().get(0).getShoppingTrolleyVOList().get(i).getGoodsPrice() + "", bean.getData().get(0).getShoppingTrolleyVOList().get(i).getGoodsAmount() + "", 2));
                count += bean.getData().get(0).getShoppingTrolleyVOList().get(i).getGoodsAmount();
            }
            tvItemPrice.setText(sum.toString());
            if (count > 0) {
                tvCartSettleaccounts.setBackgroundResource(R.drawable.corners_yellow_top_right_shape_30);
                tvShopNumber.setVisibility(View.VISIBLE);
                tvShopNumber.setText(String.valueOf(count));
            } else {
                tvCartSettleaccounts.setBackgroundResource(R.drawable.corners_gray_top_right_shape_30);
                tvShopNumber.setVisibility(View.GONE);
            }
        }

    }

    @Override
    public void getShopCouponreceive(CommonDataBean bean) {
        ToastUtils.show("领取成功");
        infoShopCouponAdapter.getData().get(mCoupunPosition).setIsReceive(true);
        infoShopCouponAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.fl_cart, R.id.tv_cart_settleaccounts, R.id.ll_shop_details_coupon, R.id.iv_collect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fl_cart:
                if (count > 0) {
                    ToastUtils.show("购物车页面");
                }
                break;
            case R.id.tv_cart_settleaccounts:
                if (count > 0) {
                    ToastUtils.show("结算页面");
                }
                break;
            case R.id.ll_shop_details_coupon://优惠券领取
//                ToastUtils.show("优惠券领取");
                if (currentShopsInfoBean.getData().getCouponList().size() > 0) {
                    showCouponDialog(currentShopsInfoBean);
                }
                break;
            case R.id.iv_collect://收藏
                ToastUtils.show("收藏店铺");
                break;
        }
    }


    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //如果注释这行，那么不管怎么切换，page都不会被销毁
            //super.destroyItem(container, position, object);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }


        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }
    }


    //**********************优惠卷start*******************************//
    CouponBottomPopup couponBottomPopup;
    private InfoShopCouponAdapter infoShopCouponAdapter;

    private int mCoupunPosition;

    //显示优惠卷对话框
    private void showCouponDialog(CurrentShopsInfoBean couponListBean) {

        couponBottomPopup = new CouponBottomPopup(this);
        couponBottomPopup.setCouponsLists(couponListBean.getData().getCouponList());
        new XPopup.Builder(this)
//                .moveUpToKeyboard(false)
                .borderRadius(8)
                .dismissOnTouchOutside(true)
                .enableDrag(false)
                .animationDuration(150)
                .asCustom(couponBottomPopup)
                .show();
    }

    /*优惠卷选择*/
    class CouponBottomPopup extends BottomPopupView {

        boolean isShow = true;

        //注意：自定义弹窗本质是一个自定义View，但是只需重写一个参数的构造，其他的不要重写，所有的自定义弹窗都是这样。
        public CouponBottomPopup(@NonNull Context context) {
            super(context);
        }

        // 返回自定义弹窗的布局
        @Override
        protected int getImplLayoutId() {
            return R.layout.dialog_shop_coupon_list;
        }

        // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
        @Override
        protected void onCreate() {
            super.onCreate();
            Button btncomfirm = findViewById(R.id.btn_dialog_comfirm);
            TextView tv_reddou = findViewById(R.id.tv_reddou);
            LinearLayout ll_cx = findViewById(R.id.ll_cx);
            TextView tv_cx = findViewById(R.id.tv_cx);
            ImageView imageView = findViewById(R.id.iv_dialog_delete);
            RecyclerView rvCoupon = findViewById(R.id.rv_dialog_coupon);
            infoShopCouponAdapter = new InfoShopCouponAdapter(mContext, R.layout.item_order_coupon_list, couponsLists);
            rvCoupon.setLayoutManager(new LinearLayoutManager(mContext));
            rvCoupon.setAdapter(infoShopCouponAdapter);
            infoShopCouponAdapter.notifyDataSetChanged();
            btncomfirm.setText("关闭");

            tv_cx.setVisibility(GONE);
            ll_cx.setVisibility(GONE);
            for (int i = 0; i < couponsLists.size(); i++) {
                couponsLists.get(i).setTagSelect(false);
            }
            //显示和隐藏
            infoShopCouponAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    infoShopCouponAdapter.setThisTagPosition(position);
                    mCoupunPosition = position;
                    TextView textView = view.findViewById(R.id.tv_receive_now);
                    switch (view.getId()) {
                        case R.id.rl_isshow:
                            if (!infoShopCouponAdapter.getData().get(position).isTagSelect()) {
                                infoShopCouponAdapter.getData().get(position).setTagSelect(true);

                            } else {
                                infoShopCouponAdapter.getData().get(position).setTagSelect(false);
                            }

                            break;
                        case R.id.tv_receive_now:
                            if (textView.getText().toString().equals("立即领取")) {
                                mPresenter.getShopCouponreceive(getToken(), infoShopCouponAdapter.getData().get(position).getId());
                            }


                            //请求领取的接口

                            break;
                    }
                    infoShopCouponAdapter.notifyItemChanged(position);
                }
            });

            btncomfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();

                }
            });


            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

        }

        // 设置最大宽度，看需要而定，
        @Override
        protected int getMaxWidth() {
            return super.getMaxWidth();
        }

        // 设置最大高度，看需要而定
        @Override
        protected int getMaxHeight() {
            return super.getMaxHeight();
        }

        // 设置自定义动画器，看需要而定
        @Override
        protected PopupAnimator getPopupAnimator() {
            return super.getPopupAnimator();
        }

        protected int getPopupWidth() {
            return 0;
        }

        protected int getPopupHeight() {
            return 0;
        }

        List<CurrentShopsInfoBean.DataBean.CouponListBean> couponsLists;

        public List<CurrentShopsInfoBean.DataBean.CouponListBean> getCouponsLists() {
            return couponsLists;
        }

        public void setCouponsLists(List<CurrentShopsInfoBean.DataBean.CouponListBean> couponsLists) {
            this.couponsLists = couponsLists;
        }

    }

    //**********************优惠卷end*******************************//
}
